/*
 * File:   UpdateVitesse_WS.c
 * Author: aravelomanantsoa@gmail.com
 */

#include <stdio.h>
#include <stdlib.h>
#include "CAN_I.h"
#include "Utils.h"
#include "cJSON.h"

/* print JSON responses */
void printJSONResponse();

/* Main function */
int main(void) {
	int v, success;
	char *queryString = NULL;

	printf(CONTENT_TYPE_JSON);

	// get query String
	queryString = getenv("QUERY_STRING");

	if (queryString == NULL) {
		printJSONErrorMsg("Cannot get query string!");
		return 0;
	} else if (sscanf(queryString, "v=%d", &v) != 1) {
		printJSONErrorMsg("Invalid query string!");
	}

	success = updateVitesse((VITESSE) v);

	if (success == CANNOT_OPEN_CAN_DEVICE) {
		printJSONErrorMsg("Cannot open CAN device!");
		return 0;
	}

	if (success == CANNOT_SEND_DATA_FRAME) {
		printJSONErrorMsg("Cannot send CAN message!");
		return 0;
	}

	printJSONResponse();

	return 0;
}

void printJSONResponse() {
	cJSON *root = cJSON_CreateObject();

	/* success = TRUE */
	cJSON_AddTrueToObject(root, "success");

	printf(cJSON_Print(root));
}
